package cn.ggsaas.base.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonStreamContext;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import cn.ggsaas.base.enums.DesensitizeEnum;
import cn.ggsaas.base.util.DesensitizeUtil;

import java.io.IOException;
import java.lang.reflect.Field;

/**
 * 脱敏注解实现
 * @author liyuzhen
 * @date 2019/9/24 11:35 上午
 */
public class DesensitizeValueSerializer extends JsonSerializer<String> {


    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        JsonStreamContext outputContext = gen.getOutputContext();
        String currentName = outputContext.getCurrentName();

        if (value != null) {
            Object currentValue = outputContext.getCurrentValue();
            try {
                Field field = currentValue.getClass().getDeclaredField(currentName);
                DesensitizeValue annotation = field.getAnnotation(DesensitizeValue.class);
                if (annotation != null) {
                    DesensitizeEnum desensitizeEnum = annotation.type();
                    gen.writeString(DesensitizeUtil.desensitize(value, desensitizeEnum));
                }
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
    }
}
